<?php
/*
Template Name: Page - Search - Result
Author: Naseer (naseer@najeebmedia.com)
*/

/*ini_set('display_errors',1);
error_reporting(E_ALL);*/

global $wpdb;

$cats=explode(",",$_POST['cid']);
$canon= $_POST['canon'];
$inFrom= $_POST['inFrom'];
$inTo= $_POST['inTo'];

if(substr($inFrom,0,1)=="$") $inFrom=substr($inFrom,1,strlen($inFrom)-1);
if(substr($inTo,0,1)=="$") $inTo=substr($inTo,1,strlen($inTo)-1);

$c1= $_POST['c1'];
$c2= $_POST['c2'];
$c3= $_POST['c3'];

//echo $c1."<br>";
//echo $c2."<br>";
//echo $c3."<br>";

$qCount=2;
$query="SELECT post_id FROM wp_postmeta WHERE (meta_key = 'canon' AND meta_value = '".$canon."') 
		OR (meta_key='amount' AND meta_value >= $inFrom AND meta_value <= $inTo)";

if($c1!=0 or $c2!=0 or $c3=0){
	$query.=" OR (meta_key = 'Rentabilidad' AND (1=0 ";
	if($c1!=0)	$query.=" OR meta_value = ".$c1;
	if($c2!=0)	$query.=" OR meta_value = ".$c2;
	if($c3!=0)	$query.=" OR meta_value = ".$c3;
	$query.=") )";
	$qCount++;
}

$query.="  GROUP BY post_id HAVING count(*) = ".$qCount;
//echo "<br>".$query."<br>";

$result=$wpdb->get_results($query, ARRAY_A);

//print "<pre>";
//var_dump($result);
//print "</pre>";

$ids=array();
foreach($result as $item)
	$ids[]=$item['post_id'];

//print_r($ids);
//print_r($cats);

$args = array();
if(count($ids)>0){
	$args['post__in']=$ids;
}


if($_POST['cid']!=""){
	$args['category__and']=$cats;
}

query_posts($args);

?>

<?php if ( count($ids)>0 and have_posts() ) : ?>
	<?php while ( have_posts() ) : the_post(); ?>
	<div class="each-post">
	  <h3><a href="post-detail-page/?pid=<?php echo the_ID(); ?>"><?php echo the_title(); ?></a></h3>
		<?php 
		if (has_post_thumbnail()):  // check if the post has a Post Thumbnail assigned to it.
		?>
		  <a href="post-detail-page/?pid=<?php echo the_ID(); ?>"><?php the_post_thumbnail("search-listing"); ?></a>
		<?php
		else: 
		?>
		<a href="post-detail-page/">
		<img style="width:200px" src="http://www.franquicia-t.com/wp-content/uploads/2012/02/200px-No_image_available.svg_.png" /></a>
		<?php endif; ?>
	  <p><?php echo the_excerpt(); ?></p>
	  <div class="clearfix"></div>
	</div>
   <?php endwhile; ?>
<?php else: ?>
	<div class="each-post">
	  <h3>No Posts Found.</h3>
	  <div class="clearfix"></div>
	</div>    
<?php endif; ?>
